# −*− coding: UTF−8 −*−
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--limit', dest='limit', default=10, type='int',
            help='process at most this many records'),
    )
    help = "run some jobs from the queue"
    args = ''
    
    def handle(self, *args, **options):
        if args:
            raise CommandError('Usage is exec_queue %s' % self.args)
        
        verbosity=int(options.get('verbosity', 0))
        limit = options.get('limit', 10)
        
        from ticket.models import Ticket
        
        for i in range(limit):
            """
            this could really be more efficient. but premature optimisation
            is the hogoblin of anally retentive minds, to mash together the
            imprecations of 3 great 20th century thinkers.
            """
            t = Ticket.objects.process_next()            
            if t is None: #queue is empty
                break
            if verbosity > 0 and t.status in set(['TRANSIENT_FAILURE', 'PERMANENT_FAILURE', 'UNCAUGHT_EXCEPTION']):
                print "%s failed with status %s, error %s" % (unicode(t), t.status, t.error_msg)
            elif (verbosity>1):
                print "%s succeeded" % unicode(t)
            